package com.scmt.hmzd.helper;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scmt.hmzd.entity.*;
import com.scmt.hmzd.enums.OrderEnum;
import com.scmt.hmzd.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@EnableScheduling
@Service
@Slf4j
public class ScheduledPushHelper {
    @Autowired
    private IHmOrderService iHmOrderService;
    @Autowired
    private IHmCouponUserService iHmCouponUserService;

    @Autowired
    private IHmCouponUseRecordService iHmCouponUseRecordService;
    @Autowired
    private IHmDisableDateService iHmDisableDateService;

    @Autowired
    private IHmCommService iHmCommService;
    @Autowired
    private IHmTechnicianService iHmTechnicianService;

    @Scheduled(cron = "0 * * * * ?") //
    @Transactional(rollbackFor = Exception.class)
    public void timedTask() throws ParseException {
        log.info("定时执行取消超时的订单-------------------------------------");
        Date now = new Date();
        List<HmOrder> orders = iHmOrderService.listUnRefundOrderAndOrderItems(OrderEnum.ORDER_ERROR.getIndex(), DateUtil.offsetMinute(now, -10));
        orders.addAll(iHmOrderService.listUnRefundOrderAndOrderItems(OrderEnum.ORDER_DEFAULT.getIndex(), DateUtil.offsetMinute(now, -10)));
        if (CollectionUtil.isEmpty(orders)) {
            return;
        }
        log.info("定时取消订单数量：{}", orders.size());

        iHmOrderService.cancelOrders(orders);

        for (HmOrder order : orders) {
            //将优惠券的状态修改回去
            //查询订单所使用的优惠券列表
            List<HmCouponUseRecord> couponUseRecordList = iHmCouponUseRecordService.list(new LambdaQueryWrapper<HmCouponUseRecord>()
                    .eq(HmCouponUseRecord::getUserId, order.getUserId())
                    .eq(HmCouponUseRecord::getStatus, 2)
                    .like(HmCouponUseRecord::getOrderNumber, order.getOrderNum()));
            if (!CollectionUtils.isEmpty(couponUseRecordList)) {
                List<Long> collect = couponUseRecordList.stream().map(item -> item.getCouponUseRecordId()).collect(Collectors.toList());
                //删除优惠券使用记录
                iHmCouponUseRecordService.removeByIds(collect);

                List<Long> longList = couponUseRecordList.stream().map(item -> item.getCouponUserId()).collect(Collectors.toList());
                //修改用户优惠券状态为可用状态
                iHmCouponUserService.batchUpdateUserCouponStatus(1, longList);
            }
            //把技师占用的时间再还回去
            removeDisableDate(order.getServiceTime(), order);
        }
        log.info("定时取消订单成功！");
    }

    private void removeDisableDate(Date serviceTime, HmOrder order) throws ParseException {
        ArrayList<HmDisableDate> dateArrayList = new ArrayList<>();
        Calendar instance = Calendar.getInstance();
        instance.setTime(serviceTime);
        instance.add(Calendar.MINUTE, order.getTimeLong());
        int count = (int) Math.ceil((double) order.getTimeLong() / 30);
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hhmm = new SimpleDateFormat("HH:mm");

        instance.setTime(serviceTime); //设置预约的服务时间   向上取整
        for (int i = 1; i <= count; i++) {
            instance.add(Calendar.MINUTE, 30);//添加30分钟
            Date time = instance.getTime();
            String format = yyyyMMdd.format(time);
            String format1 = hhmm.format(time);

            HmDisableDate hmDisableDate = new HmDisableDate();
            hmDisableDate.setDisableDate(yyyyMMdd.parse(format));
            hmDisableDate.setDisableTime(format1);
            hmDisableDate.setTechnicianId(order.getTechnicianId());
            dateArrayList.add(hmDisableDate);
        }

        instance.setTime(serviceTime); //设置预约的服务时间   向下判断，这里暂时设置和往后的时间一样， 后面订规则
        for (int i = 1; i <= count; i++) {
            instance.add(Calendar.MINUTE, -30);//添加30分钟
            Date time = instance.getTime();
            String format = yyyyMMdd.format(time);
            String format1 = hhmm.format(time);

            HmDisableDate hmDisableDate = new HmDisableDate();
            hmDisableDate.setDisableDate(yyyyMMdd.parse(format));
            hmDisableDate.setDisableTime(format1);
            hmDisableDate.setTechnicianId(order.getTechnicianId());
            dateArrayList.add(hmDisableDate);
        }

        HmDisableDate hmDisableDate = new HmDisableDate();
        hmDisableDate.setDisableDate(yyyyMMdd.parse(yyyyMMdd.format(serviceTime)));
        hmDisableDate.setDisableTime(hhmm.format(serviceTime));
        hmDisableDate.setTechnicianId(order.getTechnicianId());
        dateArrayList.add(hmDisableDate);

        for (HmDisableDate hmDisableDateItem : dateArrayList) {
            QueryWrapper<HmDisableDate> hmDisableDateQueryWrapper = new QueryWrapper<>();
            hmDisableDateQueryWrapper.lambda().eq(HmDisableDate::getTechnicianId, hmDisableDateItem.getTechnicianId());
            hmDisableDateQueryWrapper.lambda().eq(HmDisableDate::getDisableDate, hmDisableDateItem.getDisableDate());
            hmDisableDateQueryWrapper.lambda().eq(HmDisableDate::getDisableTime, hmDisableDateItem.getDisableTime());
            iHmDisableDateService.remove(hmDisableDateQueryWrapper);
        }
    }


    @Scheduled(cron = "0 0 * * * ?") //
    @Transactional(rollbackFor = Exception.class)
    public void stopOrder() {
        log.info("定时将订单处理成已结束-------------------------------------");
        List<HmOrder> orders = iHmOrderService.listUnCloseOrder();
        if (CollectionUtil.isEmpty(orders)) {
            return;
        }
        log.info("超时未结束的订单：{}", orders.size());
        ArrayList<HmTechnician> hmTechnicians = new ArrayList<>();
        orders.forEach(item -> {
            item.setStatus(OrderEnum.ORDER_STOP.getIndex());
            HmTechnician hmTechnician = new HmTechnician();
            hmTechnician.setId(item.getTechnicianId());
            hmTechnician.setIsWork(1);
            hmTechnicians.add(hmTechnician);
        });
        iHmOrderService.updateBatchById(orders);
        //把服务中的技师状态都修改回可以服务
        iHmTechnicianService.updateBatchById(hmTechnicians);
        log.info("定时结束订单成功！");
    }


    @Scheduled(cron = "0 0 * * * ? ") //
    @Transactional(rollbackFor = Exception.class)
    public void settlementOrder() {
        log.info("定时将未评论的订单处理了-------------------------------------");
        Date now = new Date();
        //暂时设置为3天  24 * 60 * 3
        List<HmOrder> orders = iHmOrderService.listUnRefundOrderAndOrderItems(OrderEnum.ORDER_STOP.getIndex(), DateUtil.offsetMinute(now, 24 * 60 * 3));
        if (CollectionUtil.isEmpty(orders)) {
            return;
        }
        log.info("未评论的订单数量：{}", orders.size());
//        for (HmOrder order : orders) {
//            if(order.getIsSettled().intValue() == 0) {
//                //将钱结算给技师
//
//            }
//        }
        orders.forEach(item -> {
            item.setStatus(OrderEnum.ORDER_COMMON.getIndex());
            item.setIsSettled(1);
        });
        iHmOrderService.updateBatchById(orders);

        ArrayList<HmComm> hmCommsArr = new ArrayList<>();
        for (HmOrder order : orders) {
            HmComm hmComm = new HmComm();
            hmComm.setCreateTime(new Date());
            hmComm.setContent("好评");
            hmComm.setStatus(1);
            hmComm.setServiceScore(5);
            hmComm.setTechnicalScore(5);
            hmComm.setAnonymous(1);
            hmComm.setEvaluate(1);
            hmComm.setOrderId(order.getId());
            hmComm.setTechnicianId(order.getTechnicianId());
        }
        iHmCommService.saveBatch(hmCommsArr);
        log.info("定时处理未评论的订单成功！");
    }
}
